package controllers;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.google.gson.JsonObject;
import constants.Configurations;
import constants.Default;
import constants.system.MemberShip;
import play.Logger;
import play.mvc.results.RenderJson;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import utils.JsonUtils;
import utils.RequestHelper;
import utils.Utils;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author yangzhi
 * @date 2019/7/5
 */
public class AliyunOssController extends ApiController {


	/**
	 * 获取阿里云 oss 的签名直传信息
	 */
	public static void aliOssGetImagePolicy() {

		String name = RequestHelper.getParam("name",0);
		String oldName = RequestHelper.getParam("oldName",0);
		Long groupId =Long.parseLong(RequestHelper.getParam("groupId",0));
		String extName = RequestHelper.getParam("extName",0);
		Logger.info("name:"+name);
		Logger.info("oldName:"+oldName);
		Logger.info("groupId:"+groupId);
		Logger.info("extName:"+extName);

		// 4.数据处理
		//Map<String, Object> data = initUserData();
		Map<String, String> map = getImagePolicy(name,oldName,groupId,extName);

		// 5.json格式处理结果
		//Map<String, String> header = new LinkedHashMap<String, String>();
		map.put("Access-Control-Allow-Origin", "*");
		map.put("Access-Control-Allow-Methods", "GET, POST");
		//renderXJSON(map, header);
		renderJSON(map);
	}

	/**
	 * 获取 oss policy
	 * 此是针对 web 直传
	 */
	private static Map<String, String> getImagePolicy(String name,String oldName,Long groupId,String extName) {
		//2 商品资源
		Integer serviceId = Default.serviceId.shop;
		//1 图片，2 视频
		Integer typeId =Default.typeId.image;
		//preview  是否为视频预览图片
		Integer preview =0;

		Map<String, String> data = null;

		// 获取配置参数
		String endpoint = Configurations.endPoint;
		String accessKeyId = Configurations.accessKeyId;
		String accessKeySecret = Configurations.accessKeySecret;
		String bucket = Configurations.ossBucketImg;
		// 店铺id/分组id/
		MemberShip memberShip = MemberShip.current();
		String dir = memberShip.getId().toString();
		String host = "https://" + bucket + "." + endpoint.substring(7);
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			long expireTime = 3600;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;

			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			String callbackUrl = Configurations.callbackUrl;

			String body = "{\\\"serviceId\\\":"+serviceId+",\\\"typeId\\\":" + typeId + ",\\\"bucket\\\":\\\"" + bucket + "\\\",\\\"name\\\":"+name+",\\\"oldName\\\":\\\"" + oldName + "\\\",\\\"size\\\":${size},\\\"height\\\":${imageInfo.height},\\\"width\\\":${imageInfo.width},\\\"dir\\\":"+dir+",\\\"createBy\\\":" + dir + ",\\\"groupId\\\":" + groupId + ",\\\"extName\\\":\\\""+extName+"\\\",\\\"preview\\\":" + preview + "}";
			String callbackBody = "{\"callbackUrl\":\""+callbackUrl+"\",\"callbackBody\":\""+body+"\",\"callbackBodyType\":\"application/x-www-form-urlencoded\"}";
			Logger.info(callbackBody);

			byte[] binaryDataCallbackBody = callbackBody.getBytes("utf-8");
			String encodedCallbackBody = BinaryUtil.toBase64String(binaryDataCallbackBody);

			data = new LinkedHashMap<String, String>();
			data.put("accessid", accessKeyId);
			data.put("policy", encodedPolicy);
			data.put("signature", postSignature);
			//目录需要/
			data.put("dir", dir.concat("/"));
			data.put("host", host);
			data.put("bucket", bucket);
			data.put("expire", String.valueOf(expireEndTime / 1000));
			data.put("callback", encodedCallbackBody);
		} catch (Exception e) {
			Logger.error(e.getMessage(), e.fillInStackTrace());
		}
		return data;
	}



	/**
	 * 获取阿里云 oss 的签名直传信息
	 */
	public static void aliOssGetVideoPolicy() {

		String name = RequestHelper.getParam("name",0);
		String oldName = RequestHelper.getParam("oldName",0);
		Long groupId =Long.parseLong(RequestHelper.getParam("groupId",0));
		String extName = RequestHelper.getParam("extName",0);
		Integer playtime = RequestHelper.getIntParam("playTime");

		Logger.info("name:"+name);
		Logger.info("oldName:"+oldName);
		Logger.info("groupId:"+groupId);
		Logger.info("extName:"+extName);
		Logger.info("playtime:"+playtime);

		// 4.数据处理
		//Map<String, Object> data = initUserData();
		Map<String, String> map = getVideoPolicy(name,oldName,groupId,extName,playtime);

		// 5.json格式处理结果
		//Map<String, String> header = new LinkedHashMap<String, String>();
		map.put("Access-Control-Allow-Origin", "*");
		map.put("Access-Control-Allow-Methods", "GET, POST");
		//renderXJSON(map, header);
		renderJSON(map);
	}


	/**
	 * 获取 oss policy
	 * 此是针对 web 直传
	 */
	private static Map<String, String> getVideoPolicy(String name,String oldName,Long groupId,String extName,Integer playtime) {
		//2 商品资源
		Integer serviceId = Default.serviceId.shop;
		//1 图片，2 视频
		Integer typeId = Default.typeId.video;
		//preview  是否为视频预览图片
		Integer preview =0;

		//imageId 视频预览图片id
		Integer imageId =0;

		Map<String, String> data = null;

		// 获取配置参数
		String endpoint = Configurations.endPoint;
		String accessKeyId = Configurations.accessKeyId;
		String accessKeySecret = Configurations.accessKeySecret;
		String bucket = Configurations.ossBucketVideo;
		// 店铺id/分组id/
		MemberShip memberShip = MemberShip.current();
		String dir = memberShip.getId().toString();
		String host = "https://" + bucket + "." + endpoint.substring(7);
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			long expireTime = 3600;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;

			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			String callbackUrl = Configurations.callbackUrl;

			String body = "{\\\"serviceId\\\":"+serviceId+",\\\"typeId\\\":" + typeId + ",\\\"bucket\\\":\\\"" + bucket + "\\\",\\\"name\\\":"+name+",\\\"oldName\\\":\\\"" + oldName + "\\\",\\\"size\\\":${size},\\\"imageId\\\":"+imageId+",\\\"playtime\\\":"+playtime+",\\\"dir\\\":"+dir+",\\\"createBy\\\":" + dir + ",\\\"groupId\\\":" + groupId + ",\\\"extName\\\":\\\""+extName+"\\\",\\\"preview\\\":" + preview + "}";
			String callbackBody = "{\"callbackUrl\":\""+callbackUrl+"\",\"callbackBody\":\""+body+"\",\"callbackBodyType\":\"application/x-www-form-urlencoded\"}";
			Logger.info(callbackBody);

			byte[] binaryDataCallbackBody = callbackBody.getBytes("utf-8");
			String encodedCallbackBody = BinaryUtil.toBase64String(binaryDataCallbackBody);

			data = new LinkedHashMap<String, String>();
			data.put("accessid", accessKeyId);
			data.put("policy", encodedPolicy);
			data.put("signature", postSignature);
			//目录需要/
			data.put("dir", dir.concat("/"));
			data.put("host", host);
			data.put("bucket", bucket);
			data.put("expire", String.valueOf(expireEndTime / 1000));
			data.put("callback", encodedCallbackBody);
		} catch (Exception e) {
			Logger.error(e.getMessage(), e.fillInStackTrace());
		}
		return data;
	}


	/**
	 * 获取图片id
	 */
	public static void getFileId(){
		JsonObject data =fileDupp.getFileNameId();
		if(checkResult(data)) {
			Logger.info("getFileId:"+data.get("id").getAsString());
			renderText(data);
		}
	}

}
